<template>
  <div class="vehicle-list-bg">
    <el-card class="vehicle-list-card">
      <div class="vehicle-list-header">
        <el-button @click="goBack" icon="ArrowLeft">返回首页</el-button>
        <div class="vehicle-list-title">我的车辆</div>
        <div class="header-actions">
          <el-button @click="goViolation" icon="Warning">违章记录</el-button>
          <el-button type="primary" @click="goRegister" icon="Plus">添加车辆</el-button>
        </div>
      </div>

      <div v-if="loading" class="loading-container">
        <el-loading-spinner />
        <p>加载中...</p>
      </div>

      <div v-else-if="vehicles.length === 0" class="empty-container">
        <el-empty description="暂无车辆信息">
          <el-button type="primary" @click="goRegister">立即添加</el-button>
        </el-empty>
      </div>

      <div v-else class="vehicle-grid">
        <el-card 
          v-for="vehicle in vehicles" 
          :key="vehicle.id" 
          class="vehicle-card"
          :class="getCardClass(vehicle.status)"
        >
          <!-- 车辆状态标签 -->
          <div class="status-badge">
            <el-tag :type="getStatusType(vehicle.status)">
              {{ getStatusText(vehicle.status) }}
            </el-tag>
          </div>

          <!-- 车辆图片 -->
          <div class="vehicle-image">
            <img 
              v-if="vehicle.image_url" 
              :src="vehicle.image_url" 
              :alt="vehicle.plate_number"
              @error="handleImageError"
            />
            <div v-else class="no-image">
              <el-icon><Picture /></el-icon>
              <span>暂无图片</span>
            </div>
          </div>

          <!-- 车辆信息 -->
          <div class="vehicle-info">
            <h3 class="plate-number">{{ vehicle.plate_number }}</h3>
            <div class="vehicle-details">
              <div class="detail-item">
                <span class="label">车型：</span>
                <span class="value">{{ vehicle.model || '未知' }}</span>
              </div>
              <div class="detail-item">
                <span class="label">颜色：</span>
                <span class="value">{{ vehicle.color || '未知' }}</span>
              </div>
              <div class="detail-item">
                <span class="label">录入时间：</span>
                <span class="value">{{ formatTime(vehicle.created_at) }}</span>
              </div>
            </div>
          </div>

          <!-- 操作按钮 -->
          <div class="vehicle-actions">
            <el-button size="small" @click="viewDetail(vehicle)">查看详情</el-button>
            <el-button 
              v-if="vehicle.status === 0" 
              size="small" 
              type="primary" 
              @click="editVehicle(vehicle)"
            >
              编辑
            </el-button>
            <el-button 
              size="small" 
              type="danger" 
              @click="deleteVehicle(vehicle)"
              :disabled="vehicle.status === 1"
            >
              删除
            </el-button>
          </div>
        </el-card>
      </div>

      <!-- 车辆详情对话框 -->
      <el-dialog 
        v-model="detailDialogVisible" 
        title="车辆详情" 
        width="600px"
        :before-close="closeDetailDialog"
      >
        <div v-if="selectedVehicle" class="vehicle-detail">
          <el-descriptions :column="2" border>
            <el-descriptions-item label="车牌号码">
              {{ selectedVehicle.plate_number }}
            </el-descriptions-item>
            <el-descriptions-item label="车辆状态">
              <el-tag :type="getStatusType(selectedVehicle.status)">
                {{ getStatusText(selectedVehicle.status) }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="车辆型号">
              {{ selectedVehicle.model || '未知' }}
            </el-descriptions-item>
            <el-descriptions-item label="车辆颜色">
              {{ selectedVehicle.color || '未知' }}
            </el-descriptions-item>
            <el-descriptions-item label="录入时间">
              {{ formatTime(selectedVehicle.created_at) }}
            </el-descriptions-item>
            <el-descriptions-item label="更新时间">
              {{ formatTime(selectedVehicle.updated_at) }}
            </el-descriptions-item>
          </el-descriptions>

          <!-- 车辆图片 -->
          <div class="detail-images" v-if="vehicleImages.length > 0">
            <h4>车辆图片</h4>
            <div class="image-gallery">
              <div 
                v-for="image in vehicleImages" 
                :key="image.id" 
                class="image-item"
              >
                <img :src="image.image_url" :alt="selectedVehicle.plate_number" />
                <div class="image-info">
                  <el-tag :type="getAuditStatusType(image.audit_status)">
                    {{ getAuditStatusText(image.audit_status) }}
                  </el-tag>
                  <span class="upload-time">{{ formatTime(image.upload_time) }}</span>
                </div>
              </div>
            </div>
          </div>
        </div>
      </el-dialog>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Picture, Plus } from '@element-plus/icons-vue'
import { vehicleAPI, vehicleImageAPI } from '@/api/vehicle'

const router = useRouter()

// 数据
const vehicles = ref([])
const loading = ref(true)
const detailDialogVisible = ref(false)
const selectedVehicle = ref(null)
const vehicleImages = ref([])

// 获取车辆列表
async function fetchVehicles() {
  try {
    loading.value = true
    const userId = localStorage.getItem('userid')
    const response = await vehicleAPI.getVehicles({ user_id: userId })
    vehicles.value = response.data || []
    console.log('获取到的车辆列表:', vehicles.value)
  } catch (error) {
    console.error('获取车辆列表失败:', error)
    ElMessage.error('获取车辆列表失败')
    vehicles.value = []
  } finally {
    loading.value = false
  }
}

// 查看车辆详情
async function viewDetail(vehicle) {
  selectedVehicle.value = vehicle
  detailDialogVisible.value = true
  
  // 获取车辆图片
  try {
    console.log('获取车辆图片，车辆ID:', vehicle.id)
    const response = await vehicleImageAPI.getVehicleImages(vehicle.id)
    console.log('车辆图片响应:', response.data)
    vehicleImages.value = response.data || []
  } catch (error) {
    console.error('获取车辆图片失败:', error)
    vehicleImages.value = []
  }
}

// 关闭详情对话框
function closeDetailDialog() {
  detailDialogVisible.value = false
  selectedVehicle.value = null
  vehicleImages.value = []
}

// 编辑车辆
function editVehicle(vehicle) {
  router.push(`/vehicle/edit/${vehicle.id}`)
}

// 删除车辆
async function deleteVehicle(vehicle) {
  try {
    await ElMessageBox.confirm(
      `确定要删除车辆 ${vehicle.plate_number} 吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await vehicleAPI.deleteVehicle(vehicle.id)
    ElMessage.success('删除成功')
    fetchVehicles() // 重新获取列表
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 跳转到注册页面
function goRegister() {
  router.push('/vehicle/register')
}

// 跳转到违章记录页面
function goViolation() {
  router.push('/vehicle/violation')
}

function goBack() {
  router.push("/")
}

// 工具函数
function getStatusText(status) {
  const map = {
    0: '正常',
    1: '禁用'
  }
  return map[status] || '未知'
}

function getStatusType(status) {
  const map = {
    0: 'success',
    1: 'danger'
  }
  return map[status] || 'info'
}

function getAuditStatusText(status) {
  const map = {
    0: '未审核',
    1: '通过',
    2: '驳回'
  }
  return map[status] || '未知'
}

function getAuditStatusType(status) {
  const map = {
    0: 'warning',
    1: 'success',
    2: 'danger'
  }
  return map[status] || 'info'
}

function getCardClass(status) {
  return status === 1 ? 'disabled-card' : ''
}

function formatTime(timeStr) {
  if (!timeStr) return '--'
  return new Date(timeStr).toLocaleString('zh-CN')
}

function handleImageError(event) {
  event.target.style.display = 'none'
  event.target.nextElementSibling.style.display = 'flex'
}

onMounted(() => {
  const userId = localStorage.getItem('userid')
  if (!userId) {
    ElMessage.error('请先登录')
    router.push('/login')
    return
  }
  fetchVehicles()
})
</script>

<style scoped>
.vehicle-list-bg {
  min-height: 100vh;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  padding: 20px;
}

.vehicle-list-card {
  max-width: 1200px;
  margin: 0 auto;
  border-radius: 24px;
  box-shadow: 0 20px 60px rgba(0, 0, 0, 0.1);
  padding: 32px;
}

.vehicle-list-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 32px;
}

.header-actions {
  display: flex;
  gap: 12px;
  align-items: center;
}

.vehicle-list-title {
  font-size: 28px;
  font-weight: bold;
  color: #222;
  letter-spacing: 2px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.loading-container,
.empty-container {
  text-align: center;
  padding: 60px 0;
}

.vehicle-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
  gap: 24px;
}

.vehicle-card {
  border-radius: 16px;
  overflow: hidden;
  transition: all 0.3s ease;
  position: relative;
}

.vehicle-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 12px 40px rgba(0, 0, 0, 0.15);
}

.disabled-card {
  opacity: 0.6;
}

.status-badge {
  position: absolute;
  top: 12px;
  right: 12px;
  z-index: 2;
}

.vehicle-image {
  height: 200px;
  overflow: hidden;
  background: #f5f5f5;
  display: flex;
  align-items: center;
  justify-content: center;
}

.vehicle-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.no-image {
  display: flex;
  flex-direction: column;
  align-items: center;
  color: #999;
}

.no-image .el-icon {
  font-size: 48px;
  margin-bottom: 8px;
}

.vehicle-info {
  padding: 20px;
}

.plate-number {
  font-size: 20px;
  font-weight: bold;
  color: #333;
  margin-bottom: 12px;
  text-align: center;
}

.vehicle-details {
  space-y: 8px;
}

.detail-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 8px;
}

.label {
  color: #666;
  font-weight: 500;
}

.value {
  color: #333;
}

.vehicle-actions {
  padding: 0 20px 20px;
  display: flex;
  gap: 8px;
  justify-content: center;
}

/* 详情对话框样式 */
.vehicle-detail {
  padding: 16px 0;
}

.detail-images {
  margin-top: 24px;
}

.detail-images h4 {
  margin-bottom: 16px;
  color: #333;
}

.image-gallery {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 16px;
}

.image-item {
  border-radius: 8px;
  overflow: hidden;
  border: 1px solid #e0e0e0;
}

.image-item img {
  width: 100%;
  height: 150px;
  object-fit: cover;
}

.image-info {
  padding: 12px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: #f9f9f9;
}

.upload-time {
  font-size: 12px;
  color: #666;
}

/* 美化按钮 */
:deep(.el-button) {
  border-radius: 8px;
  font-weight: 500;
  transition: all 0.3s ease;
}

:deep(.el-button--primary) {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
}

:deep(.el-button--primary:hover) {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .vehicle-list-bg {
    padding: 16px;
  }
  
  .vehicle-list-card {
    padding: 20px;
    border-radius: 16px;
  }
  
  .vehicle-list-header {
    flex-direction: column;
    gap: 16px;
    text-align: center;
  }
  
  .vehicle-grid {
    grid-template-columns: 1fr;
  }
}
</style>
